#include "bdd.h"

uint
td_add_base (char *se, byte c_s, byte o_mode)
{
  uint sid;
  td_err = 0;
  if (get_base (root_head, se))
    {
      td_err = ALREADY_EXIST;
      return 0;
    }

  if (o_mode != O_VIRTUAL && o_mode != O_AUTO && o_mode != O_MANUAL)
    {
      td_err = INVALID_MODE;
      return 0;
    }
  if (c_s != CASE_SENS && c_s != NO_CASE_SENS)
    {
      td_err = INVALID_CASE;
      return 0;
    }

  if (!valid_basename (se))
    {
      td_err = INVALID_STRING;
      return 0;
    }

  root_head = add_base (root_head, se, c_s);
  root_head->mode = o_mode;
  root_head->case_flag = c_s;

  sid = add_session ();
  root_head->case_flag = c_s;
  sess_tab[sid]->subptr = root_head->base;
  sess_tab[sid]->rowptr = NULL;
  sess_tab[sid]->baseptr = root_head->base;
  sess_tab[sid]->rootptr = root_head;

  if (root_head->mode == O_AUTO)
    write_bdd (root_head->base);

  return (sid);
}

byte
td_add_row (unsigned int si, char *id, char *va, byte mode)
{
  session *stmp;
  stmp = get_session (si);
  td_err = 0;
  if (!stmp)
    {
      td_err = INVALID_SESSION;
      return 0;
    }

  if (!stmp->subptr)
    {
      td_err = INVALID_SUBBASE;
      return 0;
    }

  if (!valid_string (id) || !valid_string (va))
    {
      td_err = INVALID_STRING;
      return 0;
    }
    
  if (get_row (stmp->subptr->rows, id, stmp->rootptr->case_flag))
    {
      td_err = ALREADY_EXIST;
      return 0;
    }

  stmp->subptr->rows = add_row (stmp->subptr, id, va, stmp->rootptr->case_flag);
  if (mode == SELECT)
    stmp->rowptr = stmp->subptr->last_row;

  if (stmp->rootptr->mode == O_AUTO)
    write_bdd (stmp->baseptr);
  return 1;
}

byte
td_add_subbase (unsigned int si, char *id, byte mode)
{
  session *stmp;
  stmp = get_session (si);
  td_err = 0;
  if (!stmp)
    {
      td_err = INVALID_SESSION;
      return 0;
    }

  if (!stmp->subptr)
    {
      td_err = INVALID_SUBBASE;
      return 0;
    }

  if (!valid_string (id))
    {
      td_err = INVALID_STRING;
      return 0;
    }
    
  if (get_subbase (stmp->subptr->enfant, id, stmp->rootptr->case_flag))
    {
      td_err = ALREADY_EXIST;
      return 0;
    }

  stmp->subptr->enfant = add_subbase (stmp->subptr, stmp->subptr->enfant, id, stmp->rootptr->case_flag);
  if (mode == SELECT)
    stmp->subptr = stmp->subptr->der_enfant;

  if (stmp->rootptr->mode == O_AUTO)
    write_bdd (stmp->baseptr);
  return 1;
}
